package com.tianji.learning.mq;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.service.IInteractionReplyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.QA_LIKED_TIMES_KEY;

//监听点赞系统
@Slf4j
@Component
@RequiredArgsConstructor
public class LikeTimesChangeListener {
    //互动问题的回答或评论
    private final IInteractionReplyService replyService;

    //监听点赞数变更的消息，更新点赞数量
    //qa：互动问答业务
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "qa.liked.times.queue", durable = "true"),
            //点赞记录有关的交换机：like.record.topic
            exchange = @Exchange(name = LIKE_RECORD_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = QA_LIKED_TIMES_KEY
    ))
    public void listenReplyLikedTimesChange(LikedTimesDTO likedTimesDTO) {
        //likedTimesDTO：业务id，点赞数量
        log.debug("监听到回答或评论{}的点赞数变更：{}",
                likedTimesDTO.getBizId(), likedTimesDTO.getLikedTimes());

        //回答或评论表，更新对应业务id的点赞数量
        replyService.update(Wrappers.<InteractionReply>lambdaUpdate()
                .eq(InteractionReply::getId, likedTimesDTO.getBizId()) //回答或评论id
                .set(InteractionReply::getLikedTimes, likedTimesDTO.getLikedTimes())); //点赞数量
    }
}
